<template>
  <el-drawer
    size="500px"
    title="新增赞助商"
    :append-to-body="true"
    :visible="visible"
    @close="updateVisible(false)">
    <el-button type="text" icon="el-icon-circle-plus" class="add-sponsor" @click="addRow()">添加赞助商</el-button>
    <el-form
      class="table-item"
      :model="tableData"
      ref="tableData"
      :inline="true"
      label-width="100px"
      :rules="handleFormRules"
    >
      <el-table
        max-height="703px"
        :data="tableData"
        ref="table"
        tooltip-effect="dark"
        border
        stripe>
        <el-table-column label="赞助商图片" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.prizePicture'"
              :rules="handleFormRules.prizePicture"
              size="mini"
            >
              <el-upload
                :auto-upload="false"
                class="avatar-uploader flex"
                :show-file-list="false"
                :action="ossUrl"
                accept=".jpg,.jpeg,.png"
                :multiple="false"
                :on-change="(file, fileList) => {uploadClick( file, fileList,scope)}"
                :file-list="fileList"
                :before-upload="beforeAvatarUpload">
                <img v-if="scope.row.prizePicture.length" :src="scope.row.prizePicture" class="avatar">
                <div v-else class="avatar-uploader-icon flex-column">
                  <i class="el-icon-picture" style="font-size: 20px"></i>
                  <div>上传 (建议50*100)</div>
                  <div></div>
                </div>
              </el-upload>
              <!--<el-upload
                :auto-upload="false"
                accept=".jpg,.jpeg,.png"
                :on-change="onUpload"
                class="avatar-uploader flex"
                :action="ossUrl"
                :show-file-list="false"
                :on-change="(file, fileList) => {uploadClick( file, fileList,scope)}"
                :on-success="(response, file, fileList) => {handleAvatarSuccess(response, file, fileList,scope)}"
                :before-upload="beforeAvatarUpload">
                &lt;!&ndash;imgUrl 替换 scope.row.prizePicture&ndash;&gt;
                <img v-if="scope.row.prizePicture.length" :src="scope.row.prizePicture" class="avatar">
                <div v-else class="avatar-uploader-icon flex-column">
                  <i class="el-icon-picture" style="font-size: 20px"></i>
                  <div>上传 (建议50*100)</div>
                  <div></div>
                </div>
              </el-upload>-->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="red pointer" @click="deleteRow(scope.$index, tableData)">删除</div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <div class="flex-end bottom-btn">
      <el-button round @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" class="margin20" round  @click="confirm()" :loading="loading">保存</el-button>
    </div>
  </el-drawer>
</template>

<script>
  import {pointAdd} from "@/api/agent/pointAllocation";
  import {userOssSignature} from "@/api/creatCenter/material";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";

  export default {
    name: "new-sponsor",
    props: {
      visible:Boolean
    },
    data() {
      return {
        loading:false,
        //定义的表格数据
        handleFormRules: {
          prizePicture: [
            {
              required: true,
              message: '请上传图片',
              trigger: 'change',
            },
          ]
        },

        list:[],
        table:{},
        // 奖品列表数据
        tableData: [],
        fileList:[]
      }
    },
    methods:{
      /* 更新 visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },

      /* 上传 */
      onUpload(file) {
        this.fileList.push(file)
        console.log('this.fileList',this.fileList)
      },
      uploadClick(file, fileList,scope){
        console.log('file',file,'response',URL.createObjectURL(file.raw))
        this.tableData[scope.$index].prizePicture= URL.createObjectURL(file.raw)
        this.tableData[scope.$index].raw= file.raw
      },
      /* 暂未使用 */
      handleAvatarSuccess(response, file, fileList,scope){
        console.log('file',file,'response',response,URL.createObjectURL(file.raw))
        this.tableData[scope.$index].prizePicture= URL.createObjectURL(file.raw)
        this.tableData[scope.$index].raw= file.raw
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        const extension1 = file.type === "image/jpg";
        const extension2 = file.type === "image/jpeg";
        const extension3 = file.type === "image/png";
        if (!extension1 && !extension2 && !extension3) {
          this.$message.error("请上传jpg 、png、jpeg 类型图片!");
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      //  确认提交
      confirm(){
        console.log('确认提交',this.tableData)
        this.$refs.tableData.validate((valid) => {
          console.log("valid============",valid)
          if (valid) {
            if(this.tableData.length>0){
              this.loading=true
              this.uploadBj()
              // this.$emit('getSponsors',this.tableData)
            }
            else{
              this.$message.warning("请添加赞助商")
            }
            console.log('可以拿到的数据', this.tableData)
          }
          else{
            //  校检失败
          }
        })
      },

      async uploadBj(){
        // 获取文件上传签名数据
        this.data = await userOssSignature()
        console.log("this.tableData",this.tableData)
        for(let i=0;i<this.tableData.length;i++){
          if(!this.tableData[i].raw){
            break
          }
          console.log("this.tableData[i]",this.tableData[i],this.tableData[i].raw)
          let file = this.tableData[i].raw
          console.log(file)
          let filename=file.name;
          let markIndex=(filename).lastIndexOf('.');
          let suffix=filename.substring(markIndex)
          let date=new Date().getTime();
          // 构建请求参数
          let param = new FormData()
          param.append("key", this.data.dir + date+suffix)
          param.append("policy", this.data.policy)
          param.append("OSSAccessKeyId", this.data.accessId)
          param.append("success_action_status", '200')
          // param.append("callback",  this.data.callback)     //回调（not)
          param.append("signature", this.data.signature)
          param.append("file", file, file.name)
          param.append('success_action_status', '200')
          let config = {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'x-oss-callback-Authorization': getToken()
            }
          }
          console.log("suffix",suffix)
          axios.post(this.data.host, param, config).then(res => {
            if(res.status==200){
              console.log("上传图片成功=======",res)
              console.log('this.data.host',this.data.host+'/'+date+suffix)
              let url=this.data.host+'/'+date+suffix;
              this.tableData[i].icon = url
              // 如需要重复测试，请勿删除raw
              // delete this.tableData[i].raw
              // this.fileList=[]
            }
            else{
              this.loading=false
              this.$message.error('上传失败');
            }

          }).catch(err => {
            console.log(err)
          })
        }
        setTimeout(()=>{
          console.log("图片上传并删除替换prizePicture地址==========", this.tableData)
          this.$emit('getSponsors',this.tableData)
          this.loading=false
          this.updateVisible(false)
        },200)
      },

      // 增加行
      // activityType==2:大转盘最多添加6个 activityType==3:九宫格8个
      addRow () {
        var list = {
          prizePicture : '',   //奖品图片
        }
        this.tableData.unshift(list)
        console.log('tableData---------add',this.tableData)
      },

      // 删除方法
      // 删除选中行
      deleteRow(index, rows) {
        // 表单删除对应列
        // this.tableData.splice(index, 1)
        rows.splice(index, 1);
        console.log('tableData---------del',this.tableData)
      },
    }
  }
</script>

<style scoped>
  .add-sponsor{
    width: 100%;
    text-align: right;
    padding: 20px;
  }
  .table-item{
    height: calc(100vh - 140px);
    margin:0 20px 20px;
  }
  .bottom-btn{
    margin-bottom: 20px;
    position: absolute;
    bottom: 0;
    right: 0;
  }
  .avatar{
    height: 50px;
  }
</style>
